<?php
/**
 * 我的订单接口
 * User: gqn
 * Date: 2016/2/27
 */

namespace Api\Controller;
use Think\Controller;


class MyOrderController extends BaseController{

    protected  $cancelDays = 1; //未抢订单取消时间
    protected  $refundDays = 4; //退款时间 锁定期

    /**
     * 我的订单
     */
    public function index(){
        //解决跨域
        echoHeader();
//      $user_name = I('post.user_name');
//      $key = I('post.key');
        $rid = I('post.rid');
        //$this->ajaxReturn(checkRole($user_name,$rid));

        /**1：待服务 2：服务中 3：维保中 4：已结束**/
        $user_id = I('post.user_id','');
        $valuekey = I('post.valuekey','');
        $pageIndex = I('post.pageIndex','10');
        $export = I('post.export',''); //1是取新的 2旧的
        $time = I('post.time','');  //时间戳

        if($valuekey==''|| $user_id=='' || $export!=''&& $time=='' || $export==''&& $time!='' ){
            $array = array('err_code'=>1001,'err_msg'=>'参数缺失');
            $this->ajaxReturn($array);
        }
        if($valuekey=='1'){
            $status_id = '1,2,-3';
        }
        if($valuekey=='2'){
            $status_id = '-2,3,4,5,6,7';
        }
        if($valuekey=='3'){
            $status_id = '8,9,11,12,14';
        }
        if($valuekey=='4'){
            $status_id = '10,-1,13';
        }
        $data = self::checkUserIsExist($user_id);
        if(!$data['user']){
            $this->ajaxReturn($data);
        }
        $role = $data[user][identity];

        if($role =='1'){
            $user_type = 1;
            $maps['rep.user_id'] = array('eq',$user_id);
            $maps['rep.status'] = array('in',($status_id));
            if($export=='1'){
                $maps['rep.set_time'] = array('gt',$time);
            }elseif($export=='2'){
                $maps['rep.set_time'] = array('lt',$time);
            }
            $data = M()->table('zsf_repair_order rep')
                ->field("rep.repair_order_id,rep.user_id,rep.volume_list_id,rep.set_time as time,rep.worker_user_id,rep.repair_order_num_alias,rep.shipping_tel,rep.shipping_addr,(rep.total-rep.diagnosis_cost) total,rep.set_time,rep.doorplate,rep.order_time,rep.mode_charging,rep.order_type,rep.worker_tel,rep.fault_id_list,rep.book_time,rep.fault_type,rep.status,rep.category_name,rep.lat as addr_lat,rep.lng as addr_lng,wor.lat as worker_lat,wor.lng as worker_lng,rep.amount_paid,rep.diagnosis_cost,rep.fixed_price")
                ->join("LEFT JOIN zsf_user wor on wor.user_id = rep.worker_user_id")
                ->where($maps)
                ->order('rep.repair_order_id desc')->limit(0,$pageIndex)
                ->select();
            $new = $data[0]['time'];
            $counts = count($data);
            $old = $data[$counts-1]['time'];
        }else{
            $user_type = 2;
            $maps['rep.worker_user_id'] = array('eq',$user_id);
            $maps['rep.status'] = array('in',($status_id));
            if($export=='1'){
                $maps['rep.set_time'] = array('gt',$time);
            }elseif($export=='2'){
                $maps['rep.set_time'] = array('lt',$time);
            }
            $data = M()->table('zsf_repair_order rep')
                ->field("rep.repair_order_id,rep.set_time as time,rep.user_id,rep.volume_list_id,rep.worker_user_id,rep.repair_order_num_alias,rep.shipping_tel,rep.shipping_addr,(rep.total-rep.diagnosis_cost) total,rep.set_time,rep.doorplate,rep.order_time,rep.mode_charging,rep.order_type,rep.worker_tel,rep.fault_id_list,rep.book_time,rep.fault_type,rep.status,rep.category_name,rep.lat as addr_lat,rep.lng as addr_lng,wor.lat as worker_lat,wor.lng as worker_lng,rep.amount_paid,rep.diagnosis_cost,rep.fixed_price")
                ->join("LEFT JOIN zsf_user wor on wor.user_id = rep.worker_user_id")
                ->where($maps)
                ->order('rep.repair_order_id desc')->limit(0,$pageIndex)
                ->select();
            $new = $data[0]['time'];
            $counts = count($data);
            $old = $data[$counts-1]['time'];
        }
        if($data){
            foreach($data as $k=>$v){
                if($role==2){
                    if($v['volume_list_id']){
                        $volResult = M('volume_list')->field('total')->where("volume_list_id = $v[volume_list_id] and status = 2")->find();
                        $data[$k]['amount_paid'] += $volResult['total'];
                    }
                }
                $data[$k]['order_time'] = date('m-d H:i', $data[$k]['order_time']);
                $data[$k]['set_time'] = date('m-d H:i', $data[$k]['set_time']);
                if($data[$k]['worker_user_id']!=0) {
                    $distance = getDistance($data[$k]['addr_lat'], $data[$k]['addr_lng'], $data[$k]['worker_lat'], $data[$k]['worker_lng']);
                }else{
                    $distance = '-1';
                }
                $data[$k]['distance'] = $distance;
                if($data[$k]['book_time']!='0'){
                    $data[$k]['book_time'] = date('m-d H:i', $data[$k]['book_time']);
                }
                $map['fault_id'] = array('in',$data[$k]['fault_id_list']);
                $info = M('fault')->field('name')->where($map)->select();
                $names = array_column($info,'name');
                $data[$k]['fault_name'] = implode(';',$names);
                $action = M()->table('zsf_repair_order rep')->field('config.name')->join("LEFT JOIN zsf_config_status config on rep.status = config.status and config.order_type = 1 and config.user_type = $user_type")->where("rep.repair_order_id = ".$data[$k]['repair_order_id']." and rep.status in ($status_id)")->find();
                $data[$k]['action'] = $action['name'];
            }
            $array = array('new_time'=>$new,'old_time'=>$old,'err_code'=>200,'err_msg'=>$data);
            $this->ajaxReturn($array);
        }else{
            $info = array();
            $array = array('err_code'=>200,'err_msg'=>$info);
            $this->ajaxReturn($array);
        }
    }

    /**
     * 订单搜索
     */
    public function search(){
        //解决跨域
        echoHeader();
        $user_id = I('post.user_id','');
        $keyword = I('post.keyword',''); //关键字
        $data = self::checkUserIsExist($user_id);
        if(!$data['user']){
            $this->ajaxReturn($data);
        }
        $pageIndex = I('post.pageIndex','10');
        $export = I('post.export',''); //1是取新的 2旧的
        $time = I('post.time','');  //时间戳

        $role = $data['user']['identity'];
        if($keyword ==''|| $export!=''&& $time=='' || $export==''&& $time!=''){
            $array = array('err_code'=>1001,'err_msg'=>'参数缺失');
            $this->ajaxReturn($array);
        }
        $order_id = '';
        $fault_id = M('fault')->field('fault_id')->where("name like '%$keyword%'")->select();

        if($role =='1') {
            $user_type = 1;
            if($fault_id) {
                foreach ($fault_id as $k=>$v) {
                    $id = $fault_id[$k]['fault_id'];
                    $sql = "select repair_order_id from zsf_repair_order where FIND_IN_SET($id,fault_id_list) and user_id = $user_id";
                    $order = M()->query($sql);
                    $order = $names = array_column($order, 'repair_order_id');
                    $order_id = implode(',',$order);
                }
            }
            $repair = M()->query("select re.repair_order_id,ca.category_name from zsf_repair_order as re left join zsf_category as ca on re.category_id = ca.category_id where re.user_id = $user_id and re.shipping_addr like '%$keyword%' OR re.user_id = $user_id and ca.category_name like '%$keyword%'");
            foreach($repair as $d=>$u){
                $order_id.=$repair[$d]['repair_order_id'].',';
            }
        }else{
            $user_type = 2;
            if($fault_id) {
                foreach ($fault_id as $k=>$v) {
                    $id = $fault_id[$k]['fault_id'];
                    $sql = "select repair_order_id from zsf_repair_order where FIND_IN_SET($id,fault_id_list) and worker_user_id = $user_id";
                    $order = M()->query($sql);
                    $order = $names = array_column($order, 'repair_order_id');
                    $order_id = implode(',',$order);
                }
            }
            $repair = M()->query("select re.repair_order_id,ca.category_name from zsf_repair_order as re left join zsf_category as ca on re.category_id = ca.category_id where re.worker_user_id = $user_id and re.shipping_addr like '%$keyword%' OR re.worker_user_id = $user_id and ca.category_name like '%$keyword%'");
            foreach($repair as $d=>$u){
                $order_id.=$repair[$d]['repair_order_id'].',';
            }
        }

        if($order_id ==''){
            $info = array();
            $array = array('err_code'=>1009,'err_msg'=>$info);
            $this->ajaxReturn($array);
        }


        $order_array = explode(',',$order_id);
        $order_str = array_unique($order_array);
        $order_id = join(',',$order_str);
        $order_id = rtrim($order_id, ",");

        if($role =='1'){
            $maps['rep.user_id'] = array('eq',$user_id);
            $maps['rep.repair_order_id'] = array('in',($order_id));
            $maps['rep.status'] = array('neq','0');
            if($export=='1'){
                $maps['rep.set_time'] = array('gt',$time);
            }elseif($export=='2'){
                $maps['rep.set_time'] = array('lt',$time);
            }
            $data = M()->table('zsf_repair_order rep')
                ->field("rep.repair_order_id,rep.user_id,rep.worker_user_id,rep.doorplate,rep.volume_list_id,rep.set_time as time,rep.repair_order_num_alias,rep.shipping_tel,rep.shipping_addr,(rep.total-rep.diagnosis_cost) total,rep.set_time,rep.order_time,rep.mode_charging,rep.order_type,rep.worker_tel,rep.fault_id_list,rep.book_time,rep.fault_type,rep.status,rep.category_name,rep.lat as addr_lat,rep.lng as addr_lng,wor.lat as worker_lat,wor.lng as worker_lng,rep.amount_paid,rep.diagnosis_cost,rep.fixed_price")
                ->join("LEFT JOIN zsf_user wor on wor.user_id = rep.worker_user_id")
                ->where($maps)
                ->order('rep.repair_order_id desc')->limit(0,$pageIndex)
                ->select();
            $new = $data[0]['time'];
            $counts = count($data);
            $old = $data[$counts-1]['time'];
        }else{
            $maps['rep.worker_user_id'] = array('eq',$user_id);
            $maps['rep.repair_order_id'] = array('in',($order_id));
            $maps['rep.status'] = array('neq','0');
            if($export=='1'){
                $maps['rep.set_time'] = array('gt',$time);
            }elseif($export=='2'){
                $maps['rep.set_time'] = array('lt',$time);
            }
            $data = M()->table('zsf_repair_order rep')
                ->field("rep.repair_order_id,rep.user_id,rep.worker_user_id,rep.doorplate,rep.volume_list_id,rep.repair_order_num_alias,rep.shipping_tel,rep.shipping_addr,(rep.total-rep.diagnosis_cost) total,rep.set_time,rep.order_time,rep.mode_charging,rep.order_type,rep.worker_tel,rep.fault_id_list,rep.book_time,rep.fault_type,rep.status,rep.category_name,rep.lat as addr_lat,rep.lng as addr_lng,wor.lat as worker_lat,wor.lng as worker_lng,rep.amount_paid,rep.diagnosis_cost,rep.fixed_price")
                ->join("LEFT JOIN zsf_user wor on wor.user_id = rep.worker_user_id")
                ->where($maps)
                ->order('rep.repair_order_id desc')->limit(0,$pageIndex)
                ->select();
            $new = $data[0]['time'];
            $counts = count($data);
            $old = $data[$counts-1]['time'];
        }

        if($data){
            foreach($data as $k=>$v){
                if($role==2){
                    if($v['volume_list_id']){
                        $volResult = M('volume_list')->field('total')->where("volume_list_id = $v[volume_list_id] and status = 2")->find();
                        $data[$k]['amount_paid'] += $volResult['total'];
                    }
                }
                $data[$k]['order_time'] = date('m-d H:i', $data[$k]['order_time']);
                $data[$k]['set_time'] = date('m-d H:i', $data[$k]['set_time']);
                if($data[$k]['worker_user_id']!=0) {
                    $distance = getDistance($data[$k]['addr_lat'], $data[$k]['addr_lng'], $data[$k]['worker_lat'], $data[$k]['worker_lng']);
                }else{
                    $distance = '-1';
                }
                $data[$k]['distance'] = $distance;
                if($data[$k]['book_time']!='0'){
                    $data[$k]['book_time'] = date('m-d H:i', $data[$k]['book_time']);
                }
                $map['fault_id'] = array('in',$data[$k]['fault_id_list']);
                $info = M('fault')->field('name')->where($map)->select();
                $names = array_column($info, 'name');
                $data[$k]['fault_name'] = implode(';',$names);

                $action = M()->table('zsf_repair_order rep')->field('config.name')->join("LEFT JOIN zsf_config_status config on rep.status = config.status and config.order_type = 1 and config.user_type = $user_type")->where("rep.repair_order_id = ".$data[$k]['repair_order_id'])->find();
                $data[$k]['action'] = $action['name'];
            }
            $array = array('new_time'=>$new,'old_time'=>$old,'err_code'=>200,'err_msg'=>$data);
            $this->ajaxReturn($array);
        }

    }

    /**
     * 查询订单当前状态
     * @param order_id 对外id
     */

    public function getOrderStatus(){
        $order_id = I('post.order_id');
        $orderExist = M('repair_order')->field('status')->where("repair_order_num_alias = $order_id")->find();
        if($orderExist){
            $array = array('err_code'=>200,'err_msg'=>$orderExist['status']);
        }else{
            $array = array('err_code'=>403,'err_msg'=>'订单不存在');
        }
        $this->ajaxReturn($array);
    }

    /**
     * 查询当前分类的服务须知
     * @param category_id
     */

    public function getCategoryDesc(){
        $category_id = I('category_id');
        $data = M('category')->field('desc')->where("category_id = $category_id")->find();
        if($data){
            $array = array('err_code'=>200,'err_msg'=>$data);
        }else{
            $array = array('err_code'=>403,'err_msg'=>'暂无数据');
        }
        $this->ajaxReturn($array);

    }


    /**
     * 维保期脚本
     * 更新订单状态
     */

    public function check()
    {
        while (True) {
            try {
                $this->_UpdateRepairInfo();
            } catch (\Exception $e) {
                if (strpos($e->getMessage(), 'Unknown response') !== false) {
                    echo date('y-m-d h:i:s') . "rss_pop redis bug continue" . PHP_EOL;
                    continue;
                } else {
                    echo $e->getMessage();
                    echo $e->getFile() . " Line:";
                    echo $e->getLine() . "<br>";
                    echo date('y-m-d h:i:s') . " rss_pop other bug continue" . PHP_EOL;
                    continue;
                }
            }
            sleep(rand() % 3);
        }

    }



    /**
     * 更新配置项
     * @订单维保状态
     * @黑名单
     * @优惠券
     * @未抢订单状态24小时后取消
     * @维保金到账
     */
    private function _UpdateRepairInfo(){
        //判断是否过了锁定期 是否能退款
        $refund['status'] = array('eq', 8);
        $refund['is_refund'] = array('eq', 0);
        $refundOrder = M('RepairOrder')->field("repair_order_num_alias,worker_user_id,protocol_id,pay_time,repair_order_id")->where($refund)->select();
        $model = M();
        $model->startTrans();
        foreach ($refundOrder as $k => $v) {
            $updateProtocol = M("RepairOrderProtocol")->where("protocol_id = " . $v['protocol_id'])->find();
            if ($updateProtocol['m_isready'] == 0) {
                $lockTime = strtotime("$this->refundDays minutes", $v['pay_time']);
                if (time() > $lockTime) {
                    $moneyHis['user_id'] = array('eq', $v['worker_user_id']);
                    $moneyHis['protocol_id'] = array('eq', $v['protocol_id']);
                    $moneyHis['order_id'] = array('eq', $v['repair_order_id']);
                    $moneyHis['is_plus'] = array('eq', 1);
                    $moneyHis['flag'] = array('eq', 1);
                    $MoneyHistory = M("MoneyHistory")->field('total')->where($moneyHis)->find();
                    //维修金转至余额
                    if ($MoneyHistory) {
                        $maintain = $MoneyHistory['total'];
                    }
                    $masterMaintainMoney = M("UserMoney")->where("user_id = " . $v['worker_user_id'])->setInc('balance', $maintain);
                    $this->addToMoneyHistory($v['worker_user_id'], 4, $v['repair_order_id'], $v['protocol_id'], $maintain, 1, NULL, 5, "订单" . $v['repair_order_num_alias'] . ",锁定期已过,自动转至余额");
                    //查看是否有佣金奖罚
                    $reward = M("MoneyHistory")->where("user_id = $v[worker_user_id] and order_id = $v[repair_order_id] and protocol_id = $v[protocol_id] and flag = 5 and balance = 1")->find();
                    if ($reward) {
                        if ($reward[is_plus] == 0) {
                            M("UserMoney")->where("user_id = " . $v['worker_user_id'])->setDec('balance', $reward[total]);
                        } else {
                            M("UserMoney")->where("user_id = " . $v['worker_user_id'])->setInc('balance', $reward[total]);
                        }
                    }
                    //维修金里减去数目
                    $MaintainMoney = M("UserMoney")->where("user_id = " . $v['worker_user_id'])->setDec('repair_money', $maintain);
                    $this->addToMoneyHistory($v['worker_user_id'], 4, $v['repair_order_id'], $v['protocol_id'], $maintain, 0, NULL, 1, "订单" . $v['repair_order_num_alias'] . ",锁定期已过,自动转至余额");

                    //更新协议表
                    if ($masterMaintainMoney && $MaintainMoney) {
                        $updatePro['m_isready'] = 1;
                        $updatePro = M("RepairOrderProtocol")->where("protocol_id = " . $v['protocol_id'])->save($updatePro);
                    } else {
                        continue;
                    }
                    $updateRefund['is_refund'] = 1;
                    $wheRefund['repair_order_id'] = $v['repair_order_id'];
                    $updRefund = M('RepairOrder')->where($wheRefund)->save($updateRefund);

                    if($updatePro && $updRefund && $masterMaintainMoney && $MaintainMoney){
                        $model->commit();
                    }else{
                        $model->rollback();
                    }

                }
            }
        }


        //过了维保期的订单
        $data = M('repair_order')->field('worker_user_id,repair_order_id,repair_order_num_alias,protocol_id,status')->where("status = 8")->select();

        if(!empty($data)){
            foreach($data as $key=>$value) {
                $OrderHistory = M('order_status_history')->field('add_time')->where("status = 8 and order_id =" . $data[$key]['repair_order_id'])->order('add_time asc')->find();
                $OrderProtocol = M('repair_order_protocol')->field('count,unit,bond,b_isready')->where("status = 0 and order_id =" . $data[$key]['repair_order_num_alias'])->find();
                if(!$OrderProtocol){
                    $array = array("err_code" => 404, 'err_msg' =>'协议不能为空');
                    $this->ajaxReturn($array);
                }
                $unit = '';
                if ($OrderProtocol['unit'] == '周') {
                    $unit = 'week';
                }
                if ($OrderProtocol['unit'] == '月') {
                    $unit = 'month';
                }
                if ($OrderProtocol['unit'] == '年') {
                    $unit = 'year';
                }
                if ($OrderProtocol['unit'] == '分') {
                    $unit = 'minutes';
                }
                $str = strtotime("$OrderProtocol[count] $unit", $OrderHistory['add_time']);
                $now = time();
                if ($now > $str) {
                    $model = M();
                    $model->startTrans();
                    //订单状态 更改为交易成功
                    $repair['repair_order_id'] = $data[$key]['repair_order_id'];
                    $repair['status'] = '10';
                    $orderSave = M('repair_order')->save($repair);
                    //更新师傅成交单数
                    $userInfo['user_id'] = array('eq',$data[$key]['worker_user_id']);
                    $UpdateUserInfo = M('user_real_info')->where($userInfo)->setInc('complete');
                    //添加订单历史状态
                    $condition['order_type'] = '1';
                    $condition['order_id'] = $data[$key]['repair_order_id'];
                    $condition['add_time'] = time();
                    $condition['status'] = '10';
                    $orderAddHistory = M('order_status_history')->add($condition);

                    if($OrderProtocol['b_isready']==0) {
                        //维保金转至钱包余额
                        $masterMoney = M("UserMoney")->where("user_id = " . $data[$key]['worker_user_id'])->setInc('balance', $OrderProtocol['bond']);
                        $this->addToMoneyHistory($data[$key]['worker_user_id'], 4, $data[$key]['repair_order_id'], $data[$key]['protocol_id'], $OrderProtocol['bond'], 1, NULL, 5, "订单" . $data[$key]['repair_order_num_alias'] . ",维保期已过,自动转至余额");

                        //维保金里减去数目
                        $bondMoney = M("UserMoney")->where("user_id = " . $data[$key]['worker_user_id'])->setDec('repair_bond', $OrderProtocol['bond']);
                        $this->addToMoneyHistory($data[$key]['worker_user_id'], 4, $data[$key]['repair_order_id'], $data[$key]['protocol_id'], $OrderProtocol['bond'], 0, NULL, 2, "订单" . $data[$key]['repair_order_num_alias'] . ",维保期已过,自动转至余额");
                    }

                    //更新协议表
                    if($masterMoney && $bondMoney) {
                        $updatePro['b_isready'] = 1;
                        $updateProtocol = M("RepairOrderProtocol")->where("protocol_id = ".$data[$key]['protocol_id'])->save($updatePro);
                    }else{
                        continue;
                    }

                    if ($orderSave && $UpdateUserInfo && $orderAddHistory &&$masterMoney &&$bondMoney &&$updateProtocol) {
                        $model->commit();
                    } else {
                        $model->rollback();
                    }
                }
            }
        }
        //更新黑名单状态
        $blacklist = M('user_real_info')
            ->field('user_id,is_black,deadline_black,starttime_black')
            ->where("is_black = 1")->select();
//        file_put_contents('/tmp/payment.txt',"blacklist=====".var_export($blacklist,true)."\r\n",FILE_APPEND);
        if($blacklist){
            $now_time = time();
            foreach($blacklist as $k=>$v){
                $black['user_id'] = $v['user_id'];
                $end_time = strtotime("$v[deadline_black] day","$v[starttime_black]");
                if($now_time > $end_time){
                    //更新认证表状态
                    $updateReal['is_black'] = 0;
                    $updateReal['deadline_black'] = 0;
                    $updateReal['startTime_black'] = 'NUll';
                    M('user_real_info')->where($black)->save($updateReal);
                    //更新用户表状态
                    $updateMaster['master_status'] = 0;
                    M('user')->where($black)->save($updateMaster);
                }
            }
        }
        //更新优惠券状态
        $volume['is_delete'] = 0;
        $volume['end_time'] = array('lt',time());
        $volume['status'] = array('neq',0);
        $volumeList = M('volume')->field('volume_id')->where($volume)->select();
//        file_put_contents('/tmp/payment.txt',"volumeList=====".var_export($volumeList,true)."\r\n",FILE_APPEND);
        if($volumeList){
            $volumeIds = array_column($volumeList,'volume_id');
            $volumeIds = implode(',',$volumeIds);
            $updateVolume['volume_id'] = array('in',$volumeIds);
            $updateVolume['status'] = 0;
            M('volume')->save($updateVolume);
        }
        //更新用户优惠券状态
        $volList['status'] = 1;
        $volList['end_time'] = array('lt',time());
        $userVolume = M('volume_list')->field('volume_list_id')->where($volList)->select();
//        file_put_contents('/tmp/payment.txt',"UserVolumeList=====".var_export($userVolume,true)."\r\n",FILE_APPEND);
        if($userVolume){
            $userVolumeIds = array_column($userVolume,'volume_list_id');
            $userVolumeIds = implode(',',$userVolumeIds);
            $updateUserVolume['volume_list_id'] = array('in',$userVolumeIds);
            $updateUserVolume['status'] = 3;
            M('volume_list')->save($updateUserVolume);
        }
        //更新订单状态
        $unMaps['status'] = array('eq',1);
        $unFinish = M('repair_order')->where($unMaps)->select();
//        file_put_contents('/tmp/payment.txt',"unFinishRepair=====".var_export($unFinish,true)."\r\n",FILE_APPEND);
        if($unFinish) {
            foreach ($unFinish as $k => $v) {
                $cancelTime = strtotime("$this->cancelDays day", $v['set_time']);
                if (time() > $cancelTime) {
//                    file_put_contents("/tmp/payment.txt", "updateRepairInfo======" . var_export($v[repair_order_id]) . "\r\n", FILE_APPEND);
                    //修改订单状态
                    $status['status'] = -1;
                    $w['repair_order_num_alias'] = $v['repair_order_num_alias'];
                    M('repair_order')->where($w)->save($status);
                    //增加状态表
                    $OrderStatusHistory = M('OrderStatusHistory');
                    $historyData = array();
                    $historyData['order_id'] = $v['repair_order_id'];
                    $historyData['status'] = -1;
                    $historyData['order_type'] = 1;
                    $historyData['add_time'] = time();
                    $OrderStatusHistory->add($historyData);
                    //修改推送表
                    $status['status'] = 3;
                    $pw['order_id'] = $v['repair_order_id'];
                    M('pushorder')->where($pw)->save($status);
                }
            }
        }
    }


    /**
     * 消费记录
     * @param user_id 用户id
     */

    public function UserCostRecord(){
        $user_id = I('user_id');
        $pageIndex = I('post.pageIndex',1);
        $pageSize = I('post.pageSize',10);

        $maps['rep.user_id'] = $user_id;
        $maps['rep.status'] = 10;
        $counts = M()->table('zsf_repair_order rep')
            ->field("rep.repair_order_id,rep.set_time as time,rep.user_id,rep.worker_user_id,rep.repair_order_num_alias,rep.shipping_tel,rep.shipping_addr,(rep.total-rep.diagnosis_cost) total,rep.set_time,rep.order_time,rep.mode_charging,rep.order_type,rep.worker_tel,rep.fault_id_list,rep.book_time,rep.fault_type,rep.status,rep.category_name,rep.lat as addr_lat,rep.lng as addr_lng,wor.lat as worker_lat,wor.lng as worker_lng,rep.amount_paid")
            ->join("LEFT JOIN zsf_user wor on wor.user_id = rep.worker_user_id")
            ->where($maps)
            ->order('rep.repair_order_id desc')
            ->count();
        if($counts) {
            $pages = ceil($counts / $pageSize);
            $limits = ($pageIndex - 1) * $pageSize;
            $data = M()->table('zsf_repair_order rep')
                ->field("rep.repair_order_id,rep.set_time as time,rep.user_id,rep.worker_user_id,rep.repair_order_num_alias,rep.shipping_tel,rep.shipping_addr,(rep.total-rep.diagnosis_cost) total,rep.set_time,rep.order_time,rep.mode_charging,rep.order_type,rep.worker_tel,rep.fault_id_list,rep.book_time,rep.fault_type,rep.status,rep.category_name,rep.lat as addr_lat,rep.lng as addr_lng,wor.lat as worker_lat,wor.lng as worker_lng,rep.amount_paid,rep.fixed_price")
                ->join("LEFT JOIN zsf_user wor on wor.user_id = rep.worker_user_id")
                ->where($maps)
                ->order('rep.repair_order_id desc')
                ->limit($limits . ',' . $pageSize)
                ->select();
            foreach($data as $k=>$v){
                $data[$k]['order_time'] = date('m-d H:i', $data[$k]['order_time']);
                $data[$k]['set_time'] = date('m-d H:i', $data[$k]['set_time']);
                if($data[$k]['worker_user_id']!=0) {
                    $distance = getDistance($data[$k]['addr_lat'], $data[$k]['addr_lng'], $data[$k]['worker_lat'], $data[$k]['worker_lng']);
                }else{
                    $distance = '-1';
                }
                $data[$k]['distance'] = $distance;
                if($data[$k]['book_time']!='0'){
                    $data[$k]['book_time'] = date('m-d H:i', $data[$k]['book_time']);
                }
                $map['fault_id'] = array('in',$data[$k]['fault_id_list']);
                $info = M('fault')->field('name')->where($map)->select();
                $names = array_column($info,'name');
                $data[$k]['fault_name'] = implode(';',$names);
                $action = M()->table('zsf_repair_order rep')->field('config.name')->join("LEFT JOIN zsf_config_status config on rep.status = config.status and config.order_type = 1 and config.user_type = 1")->where("rep.repair_order_id = ".$data[$k][repair_order_id]." and rep.status = 10")->find();
                $data[$k]['action'] = $action['name'];
            }
            $array = array("pages"=>$pages,"err_code"=>200,"err_msg"=>$data);
        }else{
            $info = array();
            $array = array("err_code"=>200,"err_msg"=>$info);
        }
        $this->ajaxReturn($array);


    }


    public function threeDayUncomment()
    {
        $where['user_comment'] = 0;
        $ti=time();
        $time = $ti - 60 * 60 * 24 * 3;
       // $time = $ti - 60 * 5;

        $where['pay_time'] = array('between',array(1,$time));
        $where['user_comment'] = 0;
        $orders=M('repair_order')->where($where)->field('repair_order_num_alias,user_id,worker_user_id')->select();
        $ordersql=M('repair_order')->where($where)->field('repair_order_num_alias,user_id,worker_user_id')->select(false);
        if(empty($orders)){
            file_put_contents("/tmp/threeDayUncomment.txt",var_export($ordersql,true)."no order need dispose time--".var_export($orders,true)."\r\n");
            return;
        }
        foreach($orders as $k=>$v){
            $data['user_id']=$v['user_id'];
            $data['worker_user_id']=$v['worker_user_id'];
            $data['order_id']=$v['repair_order_num_alias'];
            $data['add_time']=$ti;
            M('comment_master')->add($data);
            $w['repair_order_num_alias']=$v['repair_order_num_alias'];
            $sa['user_comment']=1;
            M('repair_order')->where($w)->save($sa);
        }
        file_put_contents("/tmp/threeDayUncomment.txt","ok----".$time."\r\n");
        exit;
    }

    /**
     * 资金流水
     * @remark 维修金、维保金、小费
     */

    private function addToMoneyHistory($user_id,$type,$order_id,$protocol_id,$total,$is_plus,$balance,$flag,$remark){
        $UserMoneyHistory = M('MoneyHistory');
        $addMaps['user_id'] = $user_id;
        $addMaps['type'] = $type;
        $addMaps['order_id'] = $order_id;
        $addMaps['protocol_id'] = $protocol_id;
        $addMaps['total'] = $total;
        $addMaps['is_plus'] = $is_plus;
        $addMaps['balance'] = $balance;
        $addMaps['add_time'] = time();
        $addMaps['flag'] = $flag;
        $addMaps['remark'] = $remark;
        $UserMoneyHistory->add($addMaps);

    }

}